package impl

import (
	"context"
	"github.com/opdss/go-helper/rand"
	"github.com/starmotioncf/common/redis"
	"github.com/starmotioncf/soutchatinternal/constant/redis_key"
	"github.com/starmotioncf/soutchatinternal/model"
	"github.com/starmotioncf/soutchatinternal/repository"
	"github.com/starmotioncf/soutchatinternal/service"
	"time"
)

type userIdService struct {
	*service.Service
	userIdRepo repository.UserIdRepository
}

func NewUserIdService(s *service.Service, userIdRepo repository.UserIdRepository) service.UserIdService {
	return &userIdService{
		Service:    s,
		userIdRepo: userIdRepo,
	}
}

func (s *userIdService) Generate(ctx context.Context, generateNum int64) error {
	locker := redis.NewLocker(redis_key.UserIdGenerateLock.ToString(), s.RDB())
	if err := locker.Lock(time.Minute); err != nil {
		return err
	}
	defer locker.UnLock()
	if generateNum <= 0 {
		generateNum = 5000
	}
	//检查可用数量
	total, err := s.userIdRepo.GetAvailableTotal(ctx)
	if err != nil {
		return err
	}
	if total > generateNum {
		return nil
	}
	//拿到最后一个id
	lastUid, err := s.userIdRepo.GetLastId(ctx)
	if err != nil {
		return err
	}
	var exist bool
	var newTotal int64
	for {
		if newTotal >= generateNum {
			break
		}
		newTotal += 1
		uid := lastUid + uint64(newTotal)
		exist, err = s.userIdRepo.CheckInCustomize(ctx, uid)
		if err != nil {
			return err
		}
		if exist {
			continue
		}
		err = s.userIdRepo.Create(ctx, &model.UserId{
			Uid:    uid,
			Status: 1,
			Sort:   rand.Int(1000, 9999),
		})
		if err != nil {
			return err
		}
	}
	return nil
}
